package com.xueyi.starter.scheduling.aop;

import com.xueyi.starter.scheduling.annotations.TaskSchedulingOnly;
import com.xueyi.starter.utils.FinalUtil;
import com.xueyi.starter.utils.JedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

/**
 * 描述 任务切面
 *
 * @author 俞烨
 * @date 2024-03-13 11
 */
@Aspect
@Component
@Slf4j
@AllArgsConstructor
public class TaskSchedulingAspect {


    private final JedisUtil jedisUtil;


    @Around("@annotation(com.xueyi.starter.scheduling.annotations.TaskSchedulingOnly)")
    public void processTask(ProceedingJoinPoint pjp) throws Throwable {

        try {
            TaskSchedulingOnly taskSchedulingOnly = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(TaskSchedulingOnly.class);
            if (taskSchedulingOnly.onlyRun()) {
                Jedis jedis = jedisUtil.getJedis();
                try {
                    String serverName = "";
                    if (taskSchedulingOnly.diffServer()) {
                        String propertyName = taskSchedulingOnly.propertyName();
                        propertyName = StringUtils.hasLength(propertyName) ? propertyName : "CLUSTER_NAME";
                        String propertyServerName = System.getProperty(propertyName);
                        if (StringUtils.hasLength(propertyServerName)) {
                            serverName = "SERVER_" + propertyServerName + "_";
                        } else {
                            serverName = "SERVER_DEFAULT_";
                        }
                    }
                    try {
                        Long setnx = jedis.setnx("TASK_" + serverName + taskSchedulingOnly.taskName(), "2");
                        if (setnx == 1L) {
                            jedis.expire("TASK_" + serverName + taskSchedulingOnly.taskName(), taskSchedulingOnly.taskSecond());
                        } else {
                            return;
                        }
                    } catch (Exception e) {
                        jedis.del("TASK_" + serverName + taskSchedulingOnly.taskName());
                    }
                } finally {
                    FinalUtil.unLockAndCloseRedis(jedis);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        pjp.proceed();
    }
}
